package com.manage.controller; /**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/27 16:02
 */

import com.manage.dao.ProfileDaoImpl;
import com.manage.pojo.Profile;
import com.manage.service.ProfileService;
import com.manage.service.ProfileServiceImpl;
import com.manage.util.StrUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet(name = "UpdateServlet1", value = "/update1")
public class UpdateServlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        //1.创建文件解析工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //2.从工厂中获取解析器对象
        ServletFileUpload parser = new ServletFileUpload(factory);
        //3.解决文件名乱码问题
        parser.setHeaderEncoding("utf-8");
        //4.判断上传表单类型,如果,没有上传的图片文件,修改失败,跳转到修改页
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.sendRedirect(request.getContextPath()+"/list");
        }
        //5.调用解析器上传数据
        List<FileItem> fileItems = null;
        try {
            fileItems = parser.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        //6.获取保存文件的本地服务器目录路径(上传到项目编译后的路径位置)
        String realPath = request.getServletContext().getRealPath("/files");
        //7.判断服务器保存文件目录是否存在,如果目录不存在自动创建文件夹
        File fileDir = new File(realPath);
        if (!fileDir.exists()){
            fileDir.mkdirs();
        }
        //8.创建Profile对象
        Profile profile = new Profile();
        //Profile profile = (Profile) request.getSession().getAttribute("Profile");
        //9.遍历表单中的每一个元素
        for (FileItem fileItem : fileItems) {
            //10.判断如果是普通表单,将数据存入Profile对象中
            if (fileItem.isFormField()){
                //判断内容是否为空
                if (!StrUtils.empty(fileItem.getString())){
                    continue;
                }
                //id
                if ("id".equals(fileItem.getFieldName())){
                    profile.setId(Integer.parseInt(fileItem.getString()));
                }
                //name
                if ("name".equals(fileItem.getFieldName())){
                    profile.setName(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                }
                //birthday
                if ("birthday".equals(fileItem.getFieldName())){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        profile.setBirthday(sdf.parse(fileItem.getString()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                //gender
                if ("gender".equals(fileItem.getFieldName())){
                    profile.setGender(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                }
                //career
                if ("career".equals(fileItem.getFieldName())){
                    profile.setCareer(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                }
                //address
                if ("address".equals(fileItem.getFieldName())){
                    profile.setAddress(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                }
                //mobile
                if ("mobile".equals(fileItem.getFieldName())){
                    profile.setMobile(fileItem.getString());
                }

            } else {
                //11.判断如果是文件,获取上传文件的路径和文件名
                String filePath = fileItem.getName();

                //12.如果未上传文件,继续处理下一个字段
                if (!StrUtils.empty(filePath)){
                    continue;
                }

                //13.获取上传文件的文件名
                String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
                //14.做io操作,保存文件到服务器硬盘的指定位置,获取输入流读取文件
                InputStream inputStream = fileItem.getInputStream();
                //15.将文件保存在服务器硬盘目录+文件名,注册具体的保存路径
                FileOutputStream out = new FileOutputStream(realPath + "\\" + fileName);
                byte[] buf = new byte[1024];
                int len;
                while ((len = inputStream.read(buf))!=-1){
                    out.write(buf,0,len);
                }
                out.close();
                inputStream.close();
                //16.保存后设置Profile对象中图片保存后的路径及文件名信息
                profile.setPicture("http://localhost:8080/files/"+fileName);
            }
        }
        //17.调用service,保存Profile对象到数据库中的profile表中
        ProfileService profileService = new ProfileServiceImpl(new ProfileDaoImpl());
        profileService.updateById(profile,profile.getId());
        //18.跳转到信息列表

        response.sendRedirect(request.getContextPath() + "/list");
    }
}
